
$(function(){

window.PublicItemView = Backbone.View.extend({
	tagName: "li",
	events: {	},
	
	initialize: function() {
		_.bindAll(this, "render");
		this.model.bind("change", this.render);
		this.model.view = this;
		this.template = _.template($("#public-item-template").html());
		$(this.el).attr('id', "item-" + this.model.get('id'));
	},
	
	render: function() {
		if (this.editor === undefined) {
			$(this.el).html(this.template(this.model.toJSON()));
		}
		//this.setContent();
		this.setName();
		return this;
	},
	
	setName: function() {
		var name = this.model.get("name");
		this.$(".item-name").text(name);
		this.nameInput = this.$(".edit-item-name");
		//this.nameInput.bind("blur", this.close);
		this.nameInput.val(name);
	},
	

	editName: function() {
		$(this.el).addClass("editing"); //$(this.el);
		this.nameInput.focus();
	},
	
	close: function(editingClassName) {
		/*this.nameInput.unbind();
		this.contentInput.unbind();*/
		this.model.save({name: this.nameInput.val(), content: this.editor.attr("value")}, {silent: true});
		$("#" + this.editorId).hide();
		$(this.el).removeClass(editingClassName);
		
		this.setContent();
		this.setName();
	},
	
	updateNameOnEnter: function(e) {
		if (e.keyCode == 13) this.close("editing");
	},
	
	saveItemFromEditor: function(e) {
		e.preventDefault();
		var cont = this.editor.attr("value").replace("<br _moz_editor_bogus_node=\"TRUE\" />", "");
		if (cont === "<br />")
		{
			cont = "";
		}
		this.model.set({name: this.nameInput.val(), content: cont}, {silent: true});
		
		//this.model.save({name: this.nameInput.val(), content: "hi", done: this.model.get("done")});
		//this.editor.attr("value", "");
		var that = this;
		this.model.save(this.model.attributes, {success : function(model, response) {
			$(that.el).removeClass("editing");
			that.$(".save").hide();
			that.$(".cancel").hide();
			that.$(".edit-buttons").hide();
			$("#" + that.editorId).hide();
		}});
		this.setContent();
		this.setName();
		$("#item-list").sortable("option", "disabled", false);
	},
	
	cancelEditor: function(e) {
		e.preventDefault();
		$(this.el).removeClass("editing");
		$("#" + this.editorId).hide();
		$("#item-list").sortable("option", "disabled", false);
	},
	
	editContent: function() {
		$(this.el).addClass("editing");
		//this.contentInput.focus();
		this.editorId = "item-editor" + this.model.get("id");
		this.$("#" + this.editorId).show();
    	if (this.editor === undefined || this.editor === null)
    	{
    		this.editor = new dijit.Editor({
    			styleSheets: "/appmedia/style.css;/appmedia/blog/style.css",
      			plugins: [
        			//"collapsibletoolbar",
        			//"fullscreen", "viewsource", "|",
        			"undo", "redo", "|",
        			"cut", "copy", "paste", "|",
        			"bold", "italic", "underline", "strikethrough", "|",
        			"insertOrderedList", "insertUnorderedList", "indent", "outdent", "|",
        			//"formatBlock", "fontName", "fontSize", "||",
        			//"findreplace", "insertEntity", "blockquote", "|",
        			"createLink", "insertImage", "insertanchor",// "|",
        			//"foreColor", "hiliteColor", "|",
        			//"showblocknodes", "pastefromword",
        			// headless plugins
        			//"normalizeindentoutdent", "prettyprint",
        			//"autourllink", "dijit._editor.plugins.EnterKeyHandling"
      			],
      			height: "200px"
    		}).placeAt(this.editorId, "first");
    	}
    	/*else
    	{
			this.editor.placeAt(this.editorId,"first");    
    	}*/
    	
    	$("#item-list").sortable("option", "disabled", true);
    	
    	this.$(".edit-buttons").show();
		this.$(".save").show();
    	this.$(".cancel").show();
    	
    	var editor = this.editor;
    	var model = this.model;
		this.editor.onLoadDeferred.addCallback(function() {
          editor.attr("value", model.get("content"));
        });
    	//this.editor.attr("value", this.model.get("content"));
	},
	
	remove: function() {
		$(this.el).remove();
	},
	
	clear: function() {
		// clear model then remove model from collection to update stats view
		// destroy first...otherwise model will not have url() which depends on its collection
		this.model.clear();
		if (this.model.list !== undefined) {
			this.model.list.items.remove(this.model);
		}
	}	
})

window.ListBrowserView = Backbone.View.extend({
	el: $("#list-builder"),
	events: {},
	
	initialize: function(options) {
		
		this.statsTemplate = _.template($("#stats-template").html())
		this.mainTemplate = _.template($("#list-browser-template").html())
				
		_.bindAll(this, 
						"addOne", 
						"addAll", 
						"render",
						"renderStats"
		);
		
		if (options === null || options === undefined ||
			options.list === null || options.list === undefined)
		{
			return;
		}
		
		this.list = options.list;
		
		this.render();
		
		this.input = this.$("#new-item");
		
		this.list.items.bind("add", this.addOne);
		this.list.items.bind("refresh", this.addAll);
		this.list.items.bind("all", this.renderStats);
		
		this.photosView = new PhotoCollectionView({ "url" : this.list.photos.url, "onPhotoLoaded" : this.onPhotoLoaded });
				
		this.titleInput = $("#title-input");
		this.titleInput.html(this.list.get("title"))
		
		// if list is on server already, fetch items
		if (!this.list.isNew()) {
			this.list.items.fetch();
			
			// fetch images
			//this.list.photos.fetch();
		}
	},
	
	render: function() {
		this.$(this.el).html(this.mainTemplate({
			title: this.list.get("title"),
		}));
	},
	
	onPhotoLoaded: function() {
	},
	
	renderStats: function() {		
		this.$("#item-stats").html(this.statsTemplate({
			total: this.list.items.length,
			done: this.list.items.done().length,
			remaining: this.list.items.remaining().length
		}));
	},
	
	addOne: function(item) {
		var view = new PublicItemView({model: item});
		item.list = this.list;
		this.$("#item-list").append(view.render().el);
	},
	
	addAll: function() {
		$("#item-list").html("");
		this.list.items.each(this.addOne);
	},
	
	remove: function(item) {
		this.list.items.each(function (item) {
			if (item.view !== undefined)
			{
				item.view.remove();
			}
		});		
	}
}),


window.PublicView = Backbone.View.extend({
	el: $("#profile-page"),
	events: {
	},
	
	initialize: function(options) {
		_.bindAll(this, "onOpenList");
		
		this.listBuilderView = new ListBrowserView();
		$("#title-input").val("");
		
		if (options.username !== undefined && options.username !== null)
		{
			// fetch user's lists, but lazily populate items
			this.myListCollectionView = new MyListCollectionView({ "username": options.username });
			this.myListCollectionView.addOnOpenListListener(this.onOpenList);
		}
	},
	
	onOpenList: function(list) {
		//$(this.listBuilderView.el).html("");
		//list.items.refresh(list.items);
		//$(this.listBuilderView.el).remove();
		
		if (this.listBuilderView.list !== undefined) {
			this.listBuilderView.list.items.unbind();
			this.listBuilderView.list.items.each(function (item) {
				if (item !== undefined) {
					item.unbind();
				};
			});
			this.listBuilderView.titleInput.unbind();
			this.listBuilderView.titleInput.val("");
		}

		this.activeList = list;
		this.listBuilderView = new ListBrowserView({ "list" : list });
		//this.listBuilderView.list.fetch();
	}
})
})